<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="header-content">
        <div class="header-left">
          <button
            id="sidebar-toggle"
            class="sidebar-toggle"
            @click="toggleSidebar"
          >
            <i class="fa fa-bars"></i>
          </button>
          <div class="header-title">
            <i class="fa fa-play-circle"></i>
            <h1>YT工单管理系统</h1>
          </div>
        </div>
        <div class="header-right">
          <button class="notification-btn">
            <i class="fa fa-bell-o"></i>
            <span class="notification-badge"></span>
          </button>
          <div v-if="isLoggedIn" class="user-info">
            <img src="https://picsum.photos/id/1005/40/40" alt="用户头像" class="user-avatar">
            <span class="user-name" :class="{ visible: isMediumScreen }">管理员</span>
            <i class="fa fa-angle-down"></i>
          </div>
          <div v-else class="login-section">
            <router-link to="/login" class="login-btn">登录</router-link>
          </div>
        </div>
      </div>
    </header>

    <div class="app-body">
      <!-- 侧边栏 -->
      <aside
        id="sidebar"
        class="app-sidebar"
        :class="{'hidden': !sidebarOpen}"
      >
        <div class="sidebar-search">
          <div class="search-container">
            <input
              type="text"
              placeholder="搜索..."
              class="search-input"
            >
            <i class="fa fa-search search-icon"></i>
          </div>
        </div>
        <nav class="sidebar-nav">
          <!-- 主菜单 -->
          <div class="nav-section-title">主菜单</div>
          <router-link
            to="/"
            class="nav-link"
            :class="{ active: isActive('/') && !isSpecificRoute }"
            exact-active-class="nav-link active"
          >
            <i class="fa fa-home nav-icon"></i>
            <span class="nav-text">仪表盘</span>
          </router-link>

          <!-- 客户端菜单 -->
          <div v-if="isLoggedIn && userRole === 'client'" class="nav-section-title">客户功能</div>
          <router-link
            v-if="isLoggedIn && userRole === 'client'"
            to="/client"
            class="nav-link"
            :class="{ active: isActive('/client') && !isActive(['/client/tickets/create', '/client/tickets']) }"
          >
            <i class="fa fa-home nav-icon"></i>
            <span class="nav-text">客户主页</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'client'"
            to="/client/tickets/create"
            class="nav-link"
            :class="{ active: isActive('/client/tickets/create') }"
          >
            <i class="fa fa-plus-circle nav-icon"></i>
            <span class="nav-text">创建工单</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'client'"
            to="/client/tickets"
            class="nav-link"
            :class="{ active: isActive('/client/tickets') && !isActive('/client/tickets/create') }"
          >
            <i class="fa fa-list nav-icon"></i>
            <span class="nav-text">我的工单</span>
          </router-link>

          <!-- 员工端菜单 -->
          <div v-if="isLoggedIn && userRole === 'staff'" class="nav-section-title">员工功能</div>
          <router-link
            v-if="isLoggedIn && userRole === 'staff'"
            to="/staff"
            class="nav-link"
            :class="{ active: isActive('/staff') && !isActive('/staff/tickets') }"
          >
            <i class="fa fa-home nav-icon"></i>
            <span class="nav-text">员工主页</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'staff'"
            to="/staff/tickets"
            class="nav-link"
            :class="{ active: isActive('/staff/tickets') }"
          >
            <i class="fa fa-tasks nav-icon"></i>
            <span class="nav-text">工单处理</span>
          </router-link>

          <!-- 管理端菜单 -->
          <div v-if="isLoggedIn && userRole === 'admin'" class="nav-section-title">管理功能</div>
          <router-link
            v-if="isLoggedIn && userRole === 'admin'"
            to="/admin"
            class="nav-link"
            :class="{ active: isActive('/admin') && !isActive(['/admin/tickets', '/admin/users', '/admin/statistics', '/admin/permissions','/admin/settings']) }"
          >
            <i class="fa fa-home nav-icon"></i>
            <span class="nav-text">管理主页</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'admin'"
            to="/admin/tickets"
            class="nav-link"
            :class="{ active: isActive('/admin/tickets') }"
          >
            <i class="fa fa-list-alt nav-icon"></i>
            <span class="nav-text">工单管理</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'admin'"
            to="/admin/permissions"
            class="nav-link"
            :class="{ active: isActive('/admin/permissions') }"
          >
            <i class="fa fa-permissions nav-icon"></i>
            <span class="nav-text">权限管理</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'admin'"
            to="/admin/users"
            class="nav-link"
            :class="{ active: isActive('/admin/users') }"
          >
            <i class="fa fa-users nav-icon"></i>
            <span class="nav-text">用户管理</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'admin'"
            to="/admin/statistics"
            class="nav-link"
            :class="{ active: isActive('/admin/statistics') }"
          >
            <i class="fa fa-bar-chart nav-icon"></i>
            <span class="nav-text">统计分析</span>
          </router-link>
          <router-link
            v-if="isLoggedIn && userRole === 'admin'"
            to="/admin/settings"
            class="nav-link"
            :class="{ active: isActive('/admin/settings') }"
          >
            <i class="fa fa-cog nav-icon"></i>
            <span class="nav-text">系统设置</span>
          </router-link>

          <!-- 系统设置 -->
          <div class="nav-section-title">系统设置</div>

          <router-link to="/support" class="nav-link" :class="{ active: isActive('/support') }">
            <i class="fa fa-question-circle nav-icon"></i>
            <span class="nav-text">帮助中心</span>
          </router-link>
          <!-- 退出登录按钮 -->
          <div v-if="isLoggedIn" class="nav-section-title">设置</div>
          <a
            href="#"
            class="nav-link"
            @click="logout"
            v-if="isLoggedIn"
          >
            <i class="fa fa-sign-out nav-icon"></i>
            <span class="nav-text">退出登录</span>
          </a>
        </nav>
      </aside>

      <!-- 主内容区域 -->
      <main class="app-main">
        <router-view />
      </main>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAuth } from './composables/useAuth'

export default {
  name: 'App',
  setup() {
    const sidebarOpen = ref(true)
    const isMediumScreen = ref(false)
    const isSpecificRoute = ref(false)
    const route = useRoute()
    // 使用认证组合函数获取认证相关功能
    const { isLoggedIn, checkLoginStatus, verifyToken, logout } = useAuth()

    // 获取用户角色
    const userRole = ref('')

    // 切换侧边栏显示状态
    const toggleSidebar = () => {
      sidebarOpen.value = !sidebarOpen.value
    }

    // 检查是否为特定路由（如登录、注册页面）
    const checkSpecificRoute = () => {
      const specificRoutes = ['/login', '/register']
      isSpecificRoute.value = specificRoutes.includes(route.path)
    }

    // 检查屏幕尺寸以适配响应式布局
    const checkScreenSize = () => {
      isMediumScreen.value = window.innerWidth >= 768
      sidebarOpen.value = window.innerWidth >= 768
    }

    // 检查导航链接的激活状态
    const isActive = (paths) => {
      if (Array.isArray(paths)) {
        return paths.some(path => route.path.startsWith(path))
      }
      return route.path.startsWith(paths)
    }

    // 在组件挂载时检查登录状态
    // 首先尝试验证token，如果失败则回退到基础检查
    onMounted(async () => {
      try {
        // 尝试调用后端API验证token有效性
        await verifyToken()
      } catch (error) {
        console.error('Auth verification error:', error)
        // 如果验证失败，回退到基础检查（仅检查localStorage中是否存在token）
        checkLoginStatus()
      }

      // 获取用户角色
      userRole.value = localStorage.getItem('userRole') || ''

      // 检查屏幕尺寸和特定路由
      checkScreenSize()
      checkSpecificRoute()
      // 添加窗口大小调整事件监听器
      window.addEventListener('resize', checkScreenSize)
    })

    // 监听路由变化，更新登录状态和特定路由状态
    watch(route, () => {
      // 检查登录状态
      checkLoginStatus()
      // 获取用户角色
      userRole.value = localStorage.getItem('userRole') || ''
      // 检查是否为特定路由
      checkSpecificRoute()
    })

    // 在组件卸载前清理事件监听器
    onBeforeUnmount(() => {
      window.removeEventListener('resize', checkScreenSize)
    })

    return {
      sidebarOpen,
      isMediumScreen,
      isSpecificRoute,
      userRole,
      toggleSidebar,
      isActive,
      isLoggedIn,
      logout,
    }
  }
}
</script>

<style>
/* 传统CSS样式，用于替换App.vue中的Tailwind CSS样式 */

/* 全局样式 */
body {
  font-family: 'Inter', system-ui, sans-serif;
  margin: 0;
  padding: 0;
}

/* 主容器样式 */
.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb;
}

/* 头部导航栏样式 */
.app-header {
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 99;
}

.header-content {
  max-width: 1280px;
  margin: 0 auto;
  padding: 0.75rem 1rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.sidebar-toggle {
  display: none;
  padding: 0.5rem;
  border-radius: 0.375rem;
  border: none;
  background: none;
  cursor: pointer;
}

.sidebar-toggle:hover {
  background-color: #f3f4f6;
}

.sidebar-toggle i {
  color: #4b5563;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.header-title i {
  color: #3b82f6;
  font-size: 1.25rem;
}

.header-title h1 {
  font-size: 1.25rem;
  font-weight: bold;
  color: #1f2937;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.notification-btn {
  position: relative;
  padding: 0.5rem;
  border-radius: 50%;
  border: none;
  background: none;
  cursor: pointer;
}

.notification-btn:hover {
  background-color: #f3f4f6;
}

.notification-btn i {
  color: #4b5563;
}

.notification-badge {
  position: absolute;
  top: 0.25rem;
  right: 0.25rem;
  width: 0.5rem;
  height: 0.5rem;
  background-color: #ef4444;
  border-radius: 50%;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.user-avatar {
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  font-weight: 500;
  display: none;
}

.user-name.visible {
  display: inline;
}

/* 登录按钮样式 */
.login-btn {
  padding: 0.5rem 1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 0.375rem;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s ease;
}

.login-btn:hover {
  background-color: #2563eb;
}

/* 主体内容样式 */
.app-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏样式 */
.app-sidebar {
  background-color: #f5f5f5; /* 浅灰色 */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  width: 16rem;
  flex-shrink: 0;
  transition: all 0.3s ease;
  z-index: 20;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  display: block;
  overflow-y: auto;
  margin-top: 3.5rem; /* 为顶部导航栏留出空间 */
}

.app-sidebar.hidden {
  display: none;
}

.sidebar-search {
  padding: 1rem;
}

.search-container {
  position: relative;
}

.search-input {
  width: 100%;
  padding: 0.5rem 1rem 0.5rem 2.5rem;
  border-radius: 0.5rem;
  border: 1px solid #e5e7eb;
  outline: none;
}

.search-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

.search-icon {
  position: absolute;
  left: 0.75rem;
  top: 0.75rem;
  color: #9ca3af;
}

.sidebar-nav {
  padding: 0.5rem;
}

.nav-section-title {
  margin: 1rem 0.75rem 0.75rem;
  font-size: 1rem; /* 从 0.75rem 增加到 1rem */
  font-weight: 600;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.025em;
}

.nav-link {
  display: flex;
  align-items: center;
  padding: 0.75rem 0.5rem;
  color: #4b5563;
  border-radius: 0.5rem;
  margin-bottom: 0.25rem;
  text-decoration: none;
  transition: all 0.2s ease;
  font-size: 1.1rem; /* 从默认大小增加到 1.1rem */
}

.nav-link:hover,
.nav-link:focus {
  background-color: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  transform: translateX(2px);
}

.nav-link.active {
  background-color: #3b82f6;
  color: #fff;
  font-weight: 600;
  box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.8);
}

.nav-icon {
  width: 1.5rem;
  text-align: center;
  margin-right: 0.75rem;
}

.nav-text {
  margin-left: 0.5rem;
  font-size: 1.1rem; /* 从 0.9rem 增加到 1.1rem */
}

/* 优化滚动条样式 */
.app-sidebar::-webkit-scrollbar {
  width: 6px;
}

.app-sidebar::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.app-sidebar::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.app-sidebar::-webkit-scrollbar-thumb:hover {
  background: #bfc4c9;
}

/* 优化搜索框 */
.search-input {
  width: 100%;
  padding: 0.5rem 1rem 0.5rem 2.5rem;
  border-radius: 0.5rem;
  border: 1px solid #e5e7eb;
  outline: none;
  transition: all 0.2s ease;
}

.search-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
  transform: translateY(-1px);
}

/* 主内容区域样式 */
.app-main {
  flex: 1;
  overflow-y: auto;
  background-color: #f9fafb;
  padding: 1rem;
  margin-left: 16rem; /* 为固定侧边栏留出空间 */
}

/* 响应式设计 */
@media (min-width: 768px) {
  .user-name.visible {
    display: inline;
  }
}

@media (min-width: 1024px) {
  .sidebar-toggle {
    display: none;
  }

  .app-sidebar {
    display: block !important;
  }

  .app-main {
    padding: 1.5rem;
  }
}

@media (max-width: 1023px) {
  .sidebar-toggle {
    display: block;
  }

  .app-sidebar {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    width: 16rem;
    z-index: 100;
    margin-top: 0;
  }

  .app-sidebar.hidden {
    display: none;
  }

  .app-main {
    margin-left: 0;
  }
}
</style>
